package com.tg.app.service;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.widget.RemoteViews;
import androidx.annotation.Nullable;

import com.tg.app.R;
import com.tg.app.activity.device.DeviceListActivity;
import com.tange.base.toolkit.AppUtil;
import com.tange.base.toolkit.FileUtil;
import com.tg.appcommon.android.TGLog;

import java.io.FileOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * Describe:
 * Created by Rance Rang on 2019-06-03.
 * <p>
 * Copyright (c) Tange.Inc All rights reserved.
 */
public class UpgradeServiceEx extends Service {
    private static final String TAG = UpgradeServiceEx.class.getSimpleName();
    private static final String DOWNLOAD_URL = "DOWNLOAD_URL";

    public static void startUpgradeService(Context context, String url){
        Intent upgradeIntent = new Intent(context, UpgradeService.class);
        upgradeIntent.putExtra(DOWNLOAD_URL, url);
        context.startService(upgradeIntent);
        context.bindService(upgradeIntent, conn, Context.BIND_AUTO_CREATE);

    }

    static ServiceConnection conn = new ServiceConnection() {

        @Override

        public void onServiceDisconnected(ComponentName name) {

// TODO Auto-generated method stub

        }

        @Override

        public void onServiceConnected(ComponentName name, IBinder service) {

// TODO Auto-generated method stub

        }

    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }


    private NotificationManager nm;

    private Notification notification;

    private File tempFile = null;

    private boolean cancelUpdate = false;

    private MyHandler myHandler;

    private int download_precent = 0;

    private RemoteViews views;

    private int notificationId = 0;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        setUpNotification();//创建通知
        myHandler = new MyHandler(Looper.myLooper(), this);
// 初始化下载任务内容views
        Message message = myHandler.obtainMessage(3, 0);
        myHandler.sendMessage(message);
        // 启动线程开始执行下载任务
        String url = intent.getStringExtra(DOWNLOAD_URL);
        downloadFile(url);
        return super.onStartCommand(intent, flags, startId);

    }

    private void setUpNotification() {
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        notification = new Notification();

        notification.icon = android.R.drawable.stat_sys_download;

// notification.icon=android.R.drawable.stat_sys_download_done;

// 放置在"正在运行"栏目中

        notification.flags = Notification.FLAG_ONGOING_EVENT;

        notification.tickerText = getString(R.string.app_name) + "更新";

        notification.when = System.currentTimeMillis();

        notification.defaults = Notification.DEFAULT_LIGHTS;

// 设置任务栏中下载进程显示的views

        views = new RemoteViews(getPackageName(), R.layout.download_notify);

        notification.contentView = views;
        PendingIntent pendingIntent;
        Intent intent= new Intent(this, DeviceListActivity.class);
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
        }else {
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
        notification.contentIntent = pendingIntent;

// 将下载任务添加到任务栏中

        nm.notify(notificationId, notification);
    }


    public void downloadFile(String url) {
        final long startTime = System.currentTimeMillis();
        TGLog.i(TAG,"startTime="+startTime);
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Connection", "close")
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                TGLog.i(TAG,"download failed");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                String savePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/mapdata/download";
                if(!FileUtil.isFolderExists(savePath)){
                    FileUtil.createFolder(savePath);
                }

                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(savePath, url.substring(url.lastIndexOf("/") + 1));
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        TGLog.e(TAG,"download progress : " + progress);
                        download_precent = progress;
                        Message message = myHandler.obtainMessage(3, progress);
                        myHandler.sendMessage(message);

                        //mView.onDownloading("",progress);
                    }
                    fos.flush();
                    TGLog.e(TAG,"download success");
                    Message message = myHandler.obtainMessage(2, file);
                    myHandler.sendMessage(message);
                    TGLog.e(TAG,"totalTime="+ (System.currentTimeMillis() - startTime));
                } catch (Exception e) {
                    e.printStackTrace();
                    TGLog.e(TAG,"download failed : "+e.getMessage());
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }




    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    class MyHandler extends Handler {
        private Context context;
        public MyHandler(Looper looper, Context c) {
            super(looper);
            this.context = c;
        }

        @Override

        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg != null) {
                switch (msg.what) {
                    case 0:
                        break;
                    case 1:
                        break;
                    case 2:
                        download_precent = 0;
                        nm.cancel(notificationId);
                        AppUtil.instanllApk((File) msg.obj, context);
                        stopSelf();
                        break;

                    case 3:
                        views.setTextViewText(R.id.tvProgress, "已下载" + download_precent + "%");
                        views.setProgressBar(R.id.pbDownload, 100, download_precent, false);
                        notification.contentView = views;
                        nm.notify(notificationId, notification);
                        break;
                    case 4:
                        nm.cancel(notificationId);
                        break;

                }

            }

        }

    }
}
